﻿from jinja2_shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from communication.models import PrivateMessage
from communication.forms import PrivateMessageForm
from userprofile.models import UserProfile
from context_processor import user_context

def show_message(request, template_name, id=None, sent=False):
    #
    # Просмотр сообщений
    # если id == None, то вернется список всех сообщений пользователя(вх и исх)
    # если id != None, то вернется сообщение с pk=id
    # 
    success = []
    errors = []
    profile = request.profile
    if id is None:
        if sent:
            message_list = PrivateMessage.objects.select_related().filter(sender=profile).order_by('is_read')
        else:
            message_list = PrivateMessage.objects.select_related().filter(receiver=profile).order_by('is_read')
        return render_to_response(template_name, {'message_list': message_list, 'success': success, 'errors': errors}, context_instance=user_context(request))
    else:
        message = get_object_or_404(PrivateMessage, pk__exact=int(id))
        if not message.is_read:
            message.is_read = True
            message.save()
        message_form = PrivateMessageForm(initial={'sender':profile.id, 'receiver':message.sender.id})
        return render_to_response(template_name, {'message': message, 'message_form': message_form, 'success': success, 'errors': errors}, context_instance=user_context(request))

show_message = login_required(redirect_field_name='/messages/show/')(show_message)

def post_message(request, template_name, to=None):
    #
    # Отсылка сообщений
    # если request.method == POST, то отсылается сообщение
    # если request.method != POST, то отображается форма отправки сообщения
    #
    success = []
    errors = []
    profile = request.profile
    if request.method == "POST":
        form = PrivateMessageForm(request.POST)
        if form.is_valid():
            form.clean()
            form.save()
            form = None
            success.append(u'Вы успешно отправили сообщение')
        else:
            errors.append(u'Проверьте правильность заполнения формы')
    else:
        receiver = get_object_or_404(UserProfile, pk=to)
        form = PrivateMessageForm(initial={'sender':profile.id, 'receiver':receiver.id})
    return render_to_response(template_name, {'message_form': form, 'errors': errors, 'success': success}, context_instance=user_context(request))

post_message = login_required(redirect_field_name='/messages/post/')(post_message)
